package com.wang.mall.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.wang.mall.model.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/upload")
public class ImageUploadController {


    @PostMapping("/image")
    public R uploadImage(@RequestParam("file") MultipartFile file) throws IOException {


        String endpoint = "http://oss-cn-beijing.aliyuncs.com";
        String accessKeyId = "LTAI4GFd36j2MKyhPLiQGDYx";
        String accessKeySecret = "nC2WT5de3AQeKAt3ij624sKTIQDuvp";

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //文件夹路径
        String dir = format + "/"; // 用户上传文件时指定的前缀。
        //图片名称
        String imageName = dir + System.currentTimeMillis() + file.getOriginalFilename();
        //String imageName = "test/" + System.currentTimeMillis() + file.getOriginalFilename();

        ossClient.putObject("a332-image-upload", imageName, file.getInputStream());

        //拼接地址
        String returnUrl = "https://a332-image-upload.oss-cn-beijing.aliyuncs.com/" + imageName;

        return R.ok(returnUrl);
    }
}
